<?php

namespace app\scm\controller;

use app\admin\common\Base;
use think\Db;
use think\Session;

//以销订购看板
class purchase extends Base
{
    public function index()
    {
        $data = $this->request->param();

        if (isset($data['ajax']) && $data['ajax'] == 100) {
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);

            if (isset($data['startdate']) && isset($data['enddate'])) {
                $month = $this->get_month_start_to_end($data['startdate'], $data['enddate']);
            } else {
                $month = $this->get_month_start_to_end();
            }
            $map = [];
            $mapOr=[];
            //$map['dj_time']=['between',[$month['month_start'],$month['month_end']]];//按时间查询
            !isset($data['keyword']) || $data['keyword'] == '' ?  $map=$map:$map['b.sn|b.mark']=['like', '%'.trim($data['keyword']).'%']; //关键字（单号,备注）
            if(!isset($data['keyword']) || $data['keyword'] == ''){

            }else{
                $c = Db::name('customer')->where('name', 'like','%'.trim($data['keyword']).'%')->select();
                if(!empty($c)){
                    $c['ids'] = implode(',', array_column($c, 'id'));
                    $mapOr['b.user_id']=['in',  $c['ids']]; //供应商 
                }
            }
            !isset($data['sale_sn']) || $data['sale_sn'] == '' ?  $map=$map:$map['b.xh_sn|b.xht_sn']=['like', '%'.trim($data['sale_sn']).'%']; //销售订单号查询
            $map['b.dj_time']=['between',[$month['month_start'],$month['month_end']]];//按时间查询

            $sql = Db::name('order_good')->alias('a')->join('order b', 'a.order_id = b.id')->field('a.*,b.*,a.mark as a_mark,b.mark as b_mark,a.id as a_id,b.id as b_id');
            //$sql = $sql ->where('o_type', 'in', [0])->where('b.addtime', '>=', $month['month_start'])->where('b.addtime', '<=', $month['month_end'])->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
            $sql = $sql ->where('o_type', 'in', [0])->where(['b.is_del' => 0, 'b.enterprise_id' => $this->EnterpriseId]);
            $sql = $sql->where($map);
            $volist = $sql->order('b.addtime desc,a.id asc')->select();
           
            
            $vlist=$this->order_good_with_order_list($volist);
            //halt($vlist);
            $list0=[];
            if(!isset($data['show_end'])){
                //halt("111");
                $data['show_end']=1;
            }
            //halt($data['show_end']);
            if($data['show_end'] == 0){//已采购完成订单是否显示
                 $list0=$vlist;
                 //halt($list0);
            }else{
                foreach ($vlist as $key => $val) {
                    if($val['now_shuliang']>0){
                        array_push($list0, $val);
                    }
                }
            }

            $list = array_slice($list0, $start, $limit);
            $count = count($list0);
            return $this->grid_data($list, $count, $page, $limit);
        }
        return $this->fetch();
    }

    public function order_good_with_order_list($volist)
    {
        $ii = 0; //让数据表格顺序
        foreach ($volist as $key => &$val) {
            $GL = Db::name('order')->where('id', $val['xh_id'])->where('is_del',0)->find(); //找到关联购货单
            if (empty($GL)) {
                $GL = Db::name('order')->where('id', $val['xht_id'])->where('is_del',0)->find(); //找到关联购货单
            }
            if (empty($GL)) {
                $order_num = Db::name('order_good')->where('order_id', $val['id'])->where('is_del', 0)->sum("base_number");
                $ck_num = 0;
                $val['gl_dj_time']='';
                $val['gl_gh_sn']='';//购货订单号
                $val['gl_gh_shuliang']='';//以销订购数量
                $val['gl_gh_real_shuliang']='';//实际入库数量
                $val['gl_sn']='';//销货单号
                $val['gl_shuliang']='';//销货出库数量
                $val['gl_not_shuliang']=$order_num-$ck_num;//未出库数量
               

            }else{
                $stock_record = Db::name('stock_record')->where('psn', $GL['sn'])->where('pid', $GL['id'])->where('is_del', 0)->find();
                $ck_num = Db::name('stock_record_good')->where('pid', $stock_record['id'])->where('is_del', 0)->sum("number");
                $order_num = Db::name('order_good')->where('order_id', $val['id'])->where('is_del', 0)->sum("base_number");
                $val['gl_dj_time']=date('Y-m-d',$GL['dj_time']); 
                $val['gl_gh_sn']='';//购货订单号
                $val['gl_gh_shuliang']='';//以销订购数量
                $val['gl_gh_real_shuliang']='';//实际入库数量
                $val['gl_sn']=$GL['sn'];//销货单号
                
                $val['gl_shuliang']=$ck_num;//销货出库数量
                $val['gl_not_shuliang']=$order_num-$ck_num;//未出库数量
            }
            $glshuliang=Db::name('order')->alias('a')->join('order_good b', 'a.id = b.order_id')->field('a.*,b.*,a.mark as a_mark,b.mark as b_mark,a.id as a_id,b.id as b_id')->where('b.xxdd_sn', $val['sn'])->sum('b.shuliang');
           
            $val['now_shuliang']=$order_num-$ck_num-$glshuliang;//待采购数量
            $val['cg_shuliang']=$order_num-$ck_num-$glshuliang;//采购数量

            $val['dj_time']=date('Y-m-d',$val['dj_time']);
            $val['og_id'] = $val['id'];
            $g = Db::name('goods')->where('id', $val['good_id'])->find(); //商品
            $s = Db::name('store')->where('id', $val['store_id'])->find(); //仓库
            $u = Db::name('unit')->where('id', $val['unit_id'])->find(); //单位
            $c = Db::name('customer')->where('id', $val['user_id'])->find(); //客户-经销商
            $val['customer_name'] = $c['sn'] . ' ' . $c['name'];
            $val['c_cate']=Db::name('customer_category')->where('id', $c['category_id'])->value('name');
            $val['c_sn']=$c['sn'];
            $val['c_name']=$c['name'];
            $val['customer_cate_name'] = Db::name('customer_category')->where('id', $c['category_id'])->value('name');
            $val['good_name'] = $g['name'];
            $val['good_model'] = $g['model'];
            $val['good_mark'] = $g['mark'];
            $val['good_id'] = $g['id'];
            $val['g_cg_price']=Db::name('goods_price_strategy')->where('goods_id', $g['id'])->value('estimated_purchase_price'); //商品预计采购价
            $val['store_id'] = $s['id'];
            $val['store_name'] = $s['name'];
            $val['unit_name'] = $u['name'];
            $val['base_unit_name'] = Db::name('unit')->where('id', $val['base_unit_id'])->value('name'); //基本单位
            $val['xxdd_id']=$val['id'];//销货钉单id
            $val['id'] = $ii + 1;
            $ii += 1;
        }
        return $volist;
    }

    public function inven(){
        $data =$this->request->param();
        // halt($data);
        if (isset($data['ajax']) && $data['ajax'] == 100) {

            $map = '';
            $page = isset($data['page']) ? $data['page'] : 1;
            $page = intval($page);
            $limit = isset($data['rows']) ? $data['rows'] : 10;
            $limit = intval($limit);
            $start = $limit * ($page - 1);


            if ($map == '') {
                $list = Db::name('store')->where('status', 0)->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->order('sort desc,id asc')->limit($start, $limit)->select();
                $count = Db::name('store')->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            } else {
                $list = Db::name('store')->where('status', 0)->where('is_del', 0)->order('sort desc,id asc')->where('enterprise_id', $this->EnterpriseId)->limit($start, $limit)->select();
                $count = Db::name('store')->where('status', 0)->where('enterprise_id', $this->EnterpriseId)->where('is_del', 0)->count();
            }
            foreach($list as $k => $v){
                $lis = db('stock_record_good')->where('good_id',$data['id'])->where('is_del', 0)->where('enterprise_id', $this->EnterpriseId)->where('store_id',$v['id']);
                $lis = $data['unit_id'] == 0 ? $lis : $lis->where('unit_id',$data['unit_id']);
                $list[$k]['number'] = $lis->sum('use_ck');
            }

            return $this->grid_data($list, $count, $page, $limit);
       }
    }

    public function inventory(){

       $data = $this->request->param();
       $this->assign('unit_id',$data['unit_id']);
       $this->assign('id',$data['id']);
       return $this->fetch();
    }

    public function edit(){
        $data=$this->request->param();
        if(!isset($data['is_znbh'])){
           $data['is_znbh']=0;
        }
        $this->assign('is_znbh',$data['is_znbh']);
         //以销代购看板start
        if(isset($data['xxdd_RowData'])){
            $xxdd_RowData=json_decode($data['xxdd_RowData'],true);
            Session::set("xxdd_RowData",$xxdd_RowData);
        }

        $this->assign('xxdd_ids',$data['xxdd_ids']);
        

         $o_type=3;
           switch ($o_type) {
                case 0:
                    $sn_name="XHDD";
                    break;
                case 1:
                    $sn_name="XH";
                    break;
                case 2:
                    $sn_name="XHT";
                    break;
                case 3:
                    $sn_name="GHDD";
                    break;
                case 4:
                    $sn_name="CG";
                    break;
                case 5:
                    $sn_name="GHT";
                    break;
                    
                default:
                    halt("参数错误");
                    break;
            }
            //订单单号XH20210813001
            $sn = osn($sn_name);
        //仓库
        $this->get_store_list();
        //销售人员
        $this->get_staff_list();
        $today = date('Y-m-d', time());
        $this->assign('today', $today);
        $this->assign('sn', $sn);
        $this->assign('admin', $this->Userinfo);
        $this->assign('o_type', $o_type);//订单类别;0,销售订单，1，销售单，2，销售退货单，3,购货订单，4，购货单，5，购货退货单
        //halt("以销代购看板");
            if (isset($data['ajax']) && $data['ajax'] == 100) {
                $page = isset($data['page']) ? $data['page'] : 1;
                $page = intval($page);
                $limit = isset($data['rows']) ? $data['rows'] : 10;
                $limit = intval($limit);
                $start = $limit * ($page - 1);
                $xxdd_RowData=Session::get("xxdd_RowData");
                if(empty($xxdd_RowData)){
                    halt("参数错误！");
                }
                $volist=[];
                $ii=0;
                foreach ($xxdd_RowData as $key => $val) {
                    //halt($val);
                    $g = Db::name('goods')->where('id', $val['good_id'])->find(); //商品
                    $volist[$ii]['good_name'] = $g['name'];
                    $volist[$ii]['good_mark'] = $g['mark'];
                    $volist[$ii]['good_id'] = $g['id'];

                    $volist[$ii]['unit_name'] =  Db::name('unit')->where('id', $g['unit'])->value('name'); //
                    $volist[$ii]['base_unit_name'] =  Db::name('unit')->where('id', $g['unit'])->value('name'); //
                    if($data['is_znbh']==1){
                        $volist[$ii]['shuliang'] = $val['jy_num'];
                        $volist[$ii]['base_number'] = $val['jy_num'];
                        $volist[$ii]['price'] = 0;//购货单价
                        $volist[$ii]['xxdd_id']=0;
                    }else{
                        $volist[$ii]['shuliang'] = $val['cg_shuliang'];
                        $volist[$ii]['base_number'] = $val['cg_shuliang'];
                        $volist[$ii]['price'] = $val['g_cg_price'];//购货单价
                        $volist[$ii]['xxdd_sn'] = $val['sn'];
                        $volist[$ii]['xxdd_id'] = $val['xxdd_id'];
                    }
                   
                    $volist[$ii]['tax_lv']=Db::name('system')->where('id', 1)->value('tax_rate')*100;//税率
                    $volist[$ii]['hs_price'] = sprintf("%.2f", $volist[$ii]['price']*(1+ $volist[$ii]['tax_lv']/100));//含税单价
                   
                    $discount_rate_one=Db::name('goods_price_strategy')->where('goods_id', $g['id'])->where('is_del',0)->value('discount_rate_one');
                    $volist[$ii]['zk_lv']=sprintf("%.2f",$discount_rate_one*100);//折扣率
                    $volist[$ii]['zk_e']=sprintf("%.2f",$volist[$ii]['price']*$volist[$ii]['zk_lv']/100*$volist[$ii]['shuliang']);//采购价*数量*折扣率
                    $volist[$ii]['jine']=sprintf("%.2f",floatval($volist[$ii]['price'])*(1-floatval($volist[$ii]['zk_lv'])/100)*floatval($volist[$ii]['shuliang']));
                    $volist[$ii]['tax_e']=sprintf("%.2f",$volist[$ii]['jine']* $volist[$ii]['tax_lv']/100*$volist[$ii]['shuliang']);
                    $volist[$ii]['total_price']=sprintf("%.2f",floatval($volist[$ii]['jine'])+floatval($volist[$ii]['tax_e']));

                   
                    $val['id'] = $ii + 1;
                    $ii+=1;
                }
                $count = count($volist);
                $list=$volist;
                // //少于5条则填充
                if(5-$count>0){
                    for ($i=0; $i <5-$count ; $i++) { 
                        array_push($list, ['id'=>$count+$i+1]);
                    }
                }
                return $this->grid_data($list, $count, $page, $limit);
            }
           
        //以销代购看板end
      
        return $this->fetch();
    }
}
